package com.milk.web.interceptor;


import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.boot.autoconfigure.dubbo.annotation.AutowiredDubbo;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.milk.model.entity.admin.Admin;
import com.milk.service.admin.AdminService;
import com.milk.utils.CookieUtils;
import com.milk.web.config.SystemConfig;
import com.xiaoleilu.hutool.util.ObjectUtil;
import com.xiaoleilu.hutool.util.StrUtil;

@Component
public class AdminInterceptor implements HandlerInterceptor{
	
	//private static List<String> noRightsUrls;
	
	@AutowiredDubbo(check = false)
	private AdminService adminService;
	
//	static{
//		noRightsUrls = new ArrayList<String>();
//		noRightsUrls.add("/manager/admin/login.do");
//	}

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String path = request.getRequestURI();
		boolean flag = true;
		//if(!noRightsUrls.contains(path)){
			Admin admin = (Admin) request.getSession().getAttribute(SystemConfig.ADMIN_SESSION_ID);
			if(ObjectUtil.isNull(admin)){
				String adminId = CookieUtils.getDecodeCookieValue(request, SystemConfig.ADMIN_COOKIE_ID);
				if(StrUtil.isNotEmpty(adminId)){
					admin = adminService.findById(Long.valueOf(adminId));
				}
			}
			if(ObjectUtil.isNull(admin)){
				PrintWriter writer = response.getWriter();
				writer.write("no-login");
				writer.flush();
				writer.close();
				flag = false;
			}else{
				//request.getSession().setAttribute(SystemConfig.ADMIN_SESSION_ID, admin);
				request.setAttribute(SystemConfig.ADMIN_SESSION_ID, admin);
			}
		//}
		return flag;
	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		
	}

	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

}
